package edu.gzhu.guli.back.service.permission;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import edu.gzhu.guli.core.entity.Permission;

@Component
public class PermissionCascadeConverter {
  public List<PermissionCascadeDto> convert(List<Permission> permissions) {
    Map<Long, PermissionCascadeDto> mapTop = new HashMap<>();
    Map<Long, PermissionCascadeDto> mapMid = new HashMap<>();
    for (Permission permission : permissions) {
      Long pid = permission.getPid();
      if (permission.getLevel() == 1) {
        mapTop.put(permission.getId(), PermissionCascadeDto.of(permission.getId(),
            permission.getPid(),
            permission.getCode(),
            permission.getName(),
            permission.getUrl(),
            permission.getLevel()));
        continue;
      }
      PermissionCascadeDto dto = PermissionCascadeDto.of(permission.getId(),
          permission.getPid(),
          permission.getCode(),
          permission.getName(),
          permission.getUrl(),
          permission.getLevel());
      if (permission.getLevel() == 2) {
        PermissionCascadeDto cascadeDto = mapTop.get(pid);
        cascadeDto.addChildren(dto);
        mapMid.put(permission.getId(), dto);
      } else {
        PermissionCascadeDto cascadeDto = mapMid.get(pid);
        cascadeDto.addChildren(dto);
      }
    }
    return new ArrayList<>(mapTop.values());
  }
}
